<template>
  <view class="hToast-wrap" v-if="isOpened">
    <view class="hToast-inner">{{message}}</view>
  </view>
</template>
<script>
import Taro from "@tarojs/taro";
export default {
  name: "hToast",
  data() {
    return {
      timer: null,
      isOpened: false,
      duration: 3000,
      message: '',
      type: ''
    }
  },
  onShow() {
    this.bindToastListener()
  },
  mounted() {
    this.bindToastListener()
  },
  beforeDestroy() {
    Taro.eventCenter.off('hToast')
  },
  methods: {
    bindToastListener() {
      Taro.eventCenter.on('hToast', (options = {}) => {
        clearTimeout(this.timer)
        const { message, title, type, duration = 3000 } = options
        this.isOpened = true
        this.message = message || title
        this.type = type
        this.duration = duration
        this.timer = setTimeout(() => {
          this.isOpened = false
        }, this.duration)
      })
      // 绑定函数
      Taro.hToast = Taro.eventCenter.trigger.bind(
        Taro.eventCenter,
        'hToast'
      )
    },
  }
}
</script>

<style>
.hToast-wrap {
  min-width: 200rpx;
  max-width: 400rpx;
  height: auto;
  position: fixed;
  left: 50%;
  top: 50%;
  text-align: center;
  transform: translate(-50%, -50%);
  color: #fff;
  font-size: 28rpx;
  background-color: rgba(0,0,0, .7);
  border-radius: 16rpx;
  padding: 10rpx;
  box-sizing: border-box;
  white-space: wrap;
}
.hToast-inner {
  width: 100%;
  height: auto;
  white-space: wrap;
  word-break: break-word;
}
</style>
